local H = require "packages/activities/HuanhuaFunc"

-- 修改一名角色的灵力数
---@param player ServerPlayer
---@param num integer
local function addSiritualPower(player, num)
  if num > 0 then
    player.room:addPlayerMark(player, "@!spiritualPower", num)
  else
    player.room:removePlayerMark(player, "@!spiritualPower", -num)
  end
end

-- 获知一名角色的灵力数
---@param player Player
---@return integer
local function getSpiritualPower(player)
  return player:getMark("@!spiritualPower")
end

-- 获知一名角色的聚灵技能
---@param player Player
---@return string[]
local function getJulingSkills(player)
  return player:getTableMark("JulingSkills")
end

-- 设置一名角色的聚灵技能
---@param player ServerPlayer
---@param skill string
local function setJulingSkill(player, skill)
  local room = player.room
  local juling_skills = getJulingSkills(player)
  if #juling_skills == 3 then
    local tolose = room:askForChoice(player, juling_skills, "spiritualPower&", "#JulingLose", true) or juling_skills[1]
    table.removeOne(juling_skills, tolose)
    room:handleAddLoseSkills(player, "-"..tolose)
  end
  room:handleAddLoseSkills(player, skill)
  table.insert(juling_skills, skill)
  room:setPlayerMark(player, "JulingSkills", juling_skills)
  local translate = table.map(juling_skills, function(s) return Fk:translate(s) end)
  room:setPlayerMark(player, "@JulingSkills", "<font color='gold'>" .. table.concat(translate, " ") .. "</font>")
end

-- 聚灵！
---@param player ServerPlayer
local function doJuling(player)
  local room = player.room
  local choices, beta_choices = H.getSkills(room, 3), {}
  addSiritualPower(player, -2)
  if getSpiritualPower(player) > 0 then
    table.insert(choices, "HuanhuaRefresh")
  end
  local choice = room:askForChoice(player, choices, "spiritualPower&", "#Juling-choose", true)
  if not choice then choice = choices[1] end
  if choice == "HuanhuaRefresh" then
    addSiritualPower(player, -1)
    beta_choices = H.getSkills(room, 3)
    choice = room:askForChoice(player, beta_choices, "spiritualPower&", "#Juling-choose", true)
  end
  if not choice then choice = choices[1] end
  setJulingSkill(player, choice)
  for _, t in ipairs{choices, beta_choices} do
    H.returnToSkillPool(room, table.filter(t, function(s) return s ~= "HuanhuaRefresh" and s ~= choice end))
  end
end

-- 并行选择技能（所有人同时选择）
---@param room Room
---@param skill_names string[]
local function ParallelHuanhua(room, skill_names)
  local alive_players = room.alive_players
  local selected_skills = {}
  
  -- 创建并行请求
  local req = Request:new(alive_players, "AskForChoice")
  req.focus_text = "huanhua_choice"
  req.receive_decode = false

  -- 为每个玩家设置选择数据
  for i, p in ipairs(alive_players) do
    local start_idx = (i-1)*3 + 1
    local end_idx = math.min(i*3 + 1, #skill_names)
    local sliced_skills = table.slice(skill_names, start_idx, end_idx)
    
    local choices = {}
    table.insertTableIfNeed(choices, sliced_skills)
    table.insert(choices, "DrawTwo")

    local request_data = { choices, choices, "huanhua_choice", "#huanhua-choose", true }
    req:setData(p, request_data)
    req:setDefaultReply(p, "DrawTwo")
  end

  -- 执行并行请求
  req:ask()

  -- 处理每个玩家的选择结果
  for _, p in ipairs(alive_players) do
    local choice = req:getResult(p)
    if choice == "DrawTwo" then
      p:drawCards(2, "huanhua_choice")
    else
      room:handleAddLoseSkills(p, choice)
      table.insert(selected_skills, choice)
    end
  end

  -- 将未选择的技能返回技能池
  local unused_skills = table.filter(skill_names, function(s) 
    return not table.contains(selected_skills, s) 
  end)
  H.returnToSkillPool(room, unused_skills)
end

-- 创建规则技能
local rule = fk.CreateSkill{
  name = "#huanhua_rule&",
}

-- 击杀奖励
rule:addEffect(fk.Deathed, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if data.damage then
      local killer = data.damage.from
      if killer and not killer.dead then
        killer:drawCards(3, "kill")
      end
    end
  end,
})

-- 造成伤害获得灵力（普通模式）
rule:addEffect(fk.Damage, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return target == player and not player.room.settings.enableDeputy
  end,
  on_refresh = function(self, event, target, player, data)
    addSiritualPower(player, data.damage)
  end,
})

-- 每轮幻化(强化模式)
rule:addEffect(fk.RoundStart, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return target == player and player.room.settings.enableDeputy
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:doBroadcastNotify("ShowToast", Fk:translate("huanhua_start"))
    H.doHuanhua(room)
  end,
})

-- 游戏结束判定
rule:addEffect(fk.GameOverJudge, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:setTag("SkipGameRule", true)
    if #room.alive_players == 1 then
      local winner = Fk.game_modes[room.settings.gameMode]:getWinner(player)
      if winner ~= "" then
        room:gameOver(winner)
        return true
      end
    end
  end,
})

-- 构建技能池和初始化（游戏开始时所有人同时选择技能）
rule:addEffect(fk.GameStart, {
  priority = 0.001,
  can_refresh = function(self, event, target, player, data)
    return target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local isUpgrade = room.settings.enableDeputy
    H.createSkillPool(room)
    
    if not isUpgrade then
      room:setBanner("@HuanhuaMode", "#NormalHuanhuaMode")
      for _, p in ipairs(room:getAllPlayers()) do
        room:handleAddLoseSkills(p, "spiritualPower&")
        addSiritualPower(p, 2)
      end
      
      -- 游戏开始时所有人同时选择技能
      local all_players = room:getAllPlayers()
      local skill_names = H.getSkills(room, 3 * #all_players)
      
      if #skill_names == 0 then 
        -- 如果技能池空了，给所有玩家摸两张牌
        for _, p in ipairs(all_players) do
          p:drawCards(2, "huanhua_choice")
        end
      else
        -- 使用并行选择
        ParallelHuanhua(room, skill_names)
      end
      
    else
      room:setBanner("@HuanhuaMode", "#BawrlHuanhuaMode")
      -- 狂暴模式游戏开始时也进行一轮幻化
      local all_players = room:getAllPlayers()
      local skill_names = H.getSkills(room, 3 * #all_players)
      
      if #skill_names == 0 then 
        for _, p in ipairs(all_players) do
          p:drawCards(2, "huanhua_choice")
        end
      else
        ParallelHuanhua(room, skill_names)
      end
    end
  end,
})

Fk:loadTranslationTable{
  ["#huanhua_rule&"] = "幻化之战",
  ["huanhua_start"] = "幻幻无穷，生生不息",
  ["spiritualPower&"] = "聚灵",
  [":spiritualPower&"] = "回合开始时，你可以移除2枚「灵力」，从3个随机技能中选一个获得；"
  .."出牌阶段限一次，你可以移除任意枚「灵力」，摸等量的牌。",
  ["HuanhuaRefresh"] = "刷新选项",
  [":HuanhuaRefresh"] = "消耗1枚「灵力」，刷新选项！",
  ["#Juling-choose"] = "聚灵：选择以下一个技能获得",
  ["@JulingSkills"] = "",
  ["#JulingLose"] = "聚灵：技能数量超出限制，选择以下1个已有的技能失去",
  ["#JulingDraw"] = "聚灵：可以移除任意枚「灵力」，摸等量的牌",
  ["@HuanhuaMode"] = "幻化",
  ["#NormalHuanhuaMode"] = "通常模式",
  ["#BawrlHuanhuaMode"] = "狂暴模式",
  ["huanhua_choice"] = "幻化",
  ["#huanhua-choose"] = "幻化：选择一项技能获得，或摸两张牌",
}

return rule